﻿@page "/clients"
@inject IState<SearchClientsState> clientState
@inject IDispatcher dispatcher
@inject NotificationService notificationService
@inject ContextMenuService contextMenuService
@inject DialogService dialogService
@inherits Fluxor.Blazor.Web.Components.FluxorComponent
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.ClientStore;
@using SimpleIdServer.IdServer.Website.Stores.RealmStore;

<div class="row">
    <div class="col">
        <RadzenText class="mt-3 mb-3 no-margin" Text="@Global.Clients" TextStyle="TextStyle.DisplayH3" />
        <p>
            @Global.ClientsDescription
        </p>
    </div>
    <div class="col-3">
        <RadzenButton class="mb-1" Click="@(args => AddClient())" Icon="add" Text="@Global.AddClient" ButtonStyle="ButtonStyle.Primary" Size="ButtonSize.Medium"></RadzenButton>
    </div>
</div>

<RadzenDataGrid @ref="clientsGrid" 
        AllowFiltering="true" 
        AllowColumnResize="true"
        AllowAlternatingRows="false" 
        AllowSorting="true" 
        PageSize="30" 
        AllowPaging="true" 
        PagerHorizontalAlign="HorizontalAlign.Left" 
        ShowPagingSummary="true"
        IsLoading="@clientState.Value.IsLoading"
        Count="@clientState.Value.Count"
        Data="@clientState.Value.Clients"
        LoadData="@LoadData"
        RowRender="@RowRender"
        TItem="SelectableClient" 
        ColumnWidth="300px">
    <Columns>
        <RadzenDataGridColumn TItem="SelectableClient" Filterable="false" Sortable="false" Width="80px" TextAlign="TextAlign.Center">
            <HeaderTemplate>
                <RadzenCheckBox @bind-Value=@selectAll Change="@(args => ToggleAll(args))" TValue="bool" />
            </HeaderTemplate>
            <Template Context="data">
                <RadzenCheckBox @bind-Value=@data.IsSelected Change="@(args => ToggleChanged(args, data))" TValue="bool" />
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="SelectableClient" Filterable="false" Sortable="true" SortProperty="Value.ClientId" Title="@Global.Identifier" Width="80px">
            <Template Context="data">
                <RadzenLink Text="@data.Value.ClientId" Path="@($"/clients/{data.Value.ClientId}/settings")" />
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="SelectableClient" Property="Value.ClientName" Filterable="false" Sortable="false" Title="@Global.Name" Width="80px" />
        <RadzenDataGridColumn TItem="SelectableClient" Filterable="false" Sortable="false" Title="Type" Width="80px">
            <Template Context="data">
                <RadzenBadge Text="@data.Value.ClientType" IsPill="true" />
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="SelectableClient" Property="Value.UpdateDateTime" Filterable="false" Sortable="true" FormatString="{0:dd/M/yyyy HH:mm:ss}" SortOrder="SortOrder.Descending" Title="@Global.UpdateDateTime" Width="80px" />
        <RadzenDataGridColumn TItem="SelectableClient" Filterable="false" Sortable="false" FormatString="{0:dd/M/yyyy HH:mm:ss}" Width="80px" TextAlign="TextAlign.Center">
            <Template Context="data">
                <RadzenButton Icon="more_vert" Click="@(args => ShowMoreContextMenu(data, args))" />
            </Template>
        </RadzenDataGridColumn>
    </Columns>
</RadzenDataGrid>

@code {
    bool selectAll = false;
    RadzenDataGrid<SelectableClient> clientsGrid;

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if(firstRender)
        {
            SubscribeToAction<RemoveSelectedClientsSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.SelectedClientsRemoved });
                StateHasChanged();
            });
            SubscribeToAction<SelectRealmSuccessAction>((act) =>
            {
                clientsGrid.Reload();
                StateHasChanged();
            });
            SubscribeToAction<AddClientSuccessAction>(async (act) =>
            {
            });
            if (!clientState.Value.IsLoading)
                clientsGrid.Reload();
        }
    }

    void LoadData(LoadDataArgs args)
    {
        var act = new SearchClientsAction { Filter = args.Filter, OrderBy = args.OrderBy, Skip = args.Skip, Take = args.Top };
        dispatcher.Dispatch(act);
    }

    void ShowMoreContextMenu(SelectableClient client, MouseEventArgs args)
    {
        contextMenuService.Open(args, new List<ContextMenuItem>
        {
            new ContextMenuItem { Text = "Delete", Value = 1 }
        }, (a) => {
            if (a.Value.Equals(1))
            {
                var clientIds = clientState.Value.Clients?.Where(c => c.IsSelected).Select(c => c.Value.ClientId)?.ToList();
                var act = new RemoveSelectedClientsAction { ClientIds = clientIds };
                dispatcher.Dispatch(act);
                contextMenuService.Close();
            }
        });
    }

    void ToggleChanged(bool isSelected, SelectableClient client)
    {
        var act = new ToggleClientSelectionAction { IsSelected = isSelected, ClientId = client.Value.ClientId };
        dispatcher.Dispatch(act);
    }

    void ToggleAll(bool isSelected)
    {        
        var act = new ToggleAllClientSelectionAction { IsSelected = isSelected };
        dispatcher.Dispatch(act);
    }

    void RowRender(RowRenderEventArgs<SelectableClient> row)
    {
        const string className = "class";
        if (row.Data.IsNew)
            row.Attributes.Add(className, "new");
        else if (row.Data.IsSelected)
            row.Attributes.Add(className, "active");
        else if (row.Attributes.ContainsKey(className))
            row.Attributes.Remove(className);
    }

    async void AddClient() 
    {
        await dialogService.OpenAsync<AddClientDialog>(Global.AddClient, new Dictionary<string, object>(), new DialogOptions
        {
            Width = "700px",
            Height ="512px",
            Resizable = true,
            Draggable = true
        });
    }
}